package com.xxmw.transaction.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxmw.transaction.common.entity.P;
import com.xxmw.transaction.common.excep.service.TransactionException;
import com.xxmw.transaction.common.utils.Constant;
import com.xxmw.transaction.mapper.SysRoleMapper;
import com.xxmw.transaction.model.SysRole;
import com.xxmw.transaction.service.SysRoleMenuService;
import com.xxmw.transaction.service.SysRoleService;
import com.xxmw.transaction.service.SysUserRoleService;
import com.xxmw.transaction.service.SysUserService;

@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Override
	@Transactional
	public void addOrUpdate(SysRole role) {
		if (0 == role.getRoleId()) {
			role.setRoleId(null);
			role.setCreated(new Date());
		}
		this.saveOrUpdate(role);
		checkPrems(role);
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

	}

	@Override
	@Transactional
	public void deleteBatch(Long... roleIds) {
		this.removeByIds(Arrays.asList(roleIds));
		sysRoleMenuService.deleteBatch(roleIds);
		sysUserRoleService.deleteBatch(roleIds);
	}

	@Override
	public List<Long> getRoleIdList(Long adder) {
		return baseMapper.selectRoleIdList(adder);
	}

	@Override
	public P<SysRole> getList(int pageNum, int pageSize, String roleName, Long adder) {
		IPage<SysRole> page = new Page<>(pageNum, pageSize);
		QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
		wrapper.eq(StringUtils.isNotBlank(roleName) , "role_name", roleName);
		wrapper.eq(adder != null, "adder", adder);
		page(page, wrapper);
		return new P<>(page.getTotal(), page.getRecords());
	}

	private void checkPrems(SysRole role) {
		if(role.getAdder() == Constant.SUPER_ADMIN) {
			return;
		}
		List<Long> menuIdList = sysUserService.getAllMenuId(role.getAdder());
		if(!menuIdList.containsAll(role.getMenuIdList())) {
			throw new TransactionException("新增角色的权限，已超出你的权限范围");
		}
	}
}
